#-*- coding: utf-8 -*-

import sys, os
import inspect
import pmcore.basecom


def load_components(comdir,restrictfile):
    comlist = {}
    # Load list of restrict modules
    f=open(comdir+"/"+restrictfile)
    restrict = f.readlines()
    for i in xrange(len(restrict)):
        restrict[i] = restrict[i].replace("\n","")
        restrict[i] = restrict[i].replace("\r","")
    #print restrict
    f.close()


    #packages = []    
    print "\nCOMPONENTS FINDED"
    for pname in os.listdir(comdir):
        if pname not in restrict:
            if os.path.isdir(comdir + "/" + pname):
                for fname in os.listdir(comdir + "/" + pname):
                    if fname.endswith (".py"):
                        module_name = fname[: -3]
                        #if module_name not in restrict:
                        #packages.append(pname)
                        #for spname in os.listdir(pname):
                        com_pack = __import__(comdir + "." + pname + "." + module_name)
                        #print dir(com_pack)
                        pack = getattr (com_pack, pname)
                        module = getattr (pack, module_name)
                        for class_name in dir(module):
                            imp_class = getattr (module, class_name)
                            if inspect.isclass (imp_class):
                                if issubclass (imp_class, pmcore.basecom.BaseComponent):
                                    #if class_name not in comlist:
                                    if imp_class != pmcore.basecom.BaseComponent:
                                        print imp_class
                                        o = imp_class()
                                        if o.name not in comlist:
                                            comlist[o.name] = o
                                        else:
                                            print "ERROR: Duplicate component name\n"
                                            sys.exit()
    return comlist



